import { Component, OnInit, Input } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router'
import { NzMessageService, NzModalService } from 'ng-zorro-antd'
import { STColumn } from '@delon/abc'
import { ACLService } from '@delon/acl'

import { I18NService } from '@core'
import { ListBaseClass } from '@shared/classes/ListBaseClass'
import { CommonAcquirerService } from '@shared/services/acquirer.service'
import { User, IUserQueryParams } from '@shared/interfaces/user'
import { ERoleType, ETabScrollStatus, ECustomAcl } from '@shared/enums'
import { UserService } from 'app/routes/user/user.service'
import { UserAlinterService } from 'app/routes/user/user-alinter.service'
import { PageService } from '@shared/services/page.service'
import { detailUserNum } from 'app/utils/contraints'
import { Observable } from 'rxjs'

@Component({
  selector: 'app-detail-tab-users',
  templateUrl: './detail-tab-users.component.html',
  styleUrls: ['../../styles/table.less'],
  providers: [{ provide: UserService, useClass: UserAlinterService }],
})
export class TabDetailUsersComponent extends ListBaseClass<User, IUserQueryParams> implements OnInit {
  columns: STColumn[]
  @Input() insCode: string
  @Input() roleType: ERoleType
  @Input() businessParameters: { [code: string]: string }

  data: User[] = []
  size = detailUserNum

  constructor(
    public commonAcquirerService: CommonAcquirerService,
    public router: Router,
    public route: ActivatedRoute,
    public i18n: I18NService,
    public msg: NzMessageService,
    private modal: NzModalService,
    private userService: UserService,
    private pageService: PageService,
    private aclService: ACLService,
  ) {
    super(msg, i18n, route, router)
  }

  get isDisplayInTask(): Observable<boolean> {
    return this.pageService.isStoreDisplayInTask$
  }

  ngOnInit() {
    this.columns = this.createColumns()
    this.queryTableDataWithParams()
  }

  renderList(response): void {
    const { data, total } = response
    this.data = data
    this.total = total
    this.loading = false
  }

  queryTableDataWithParams(): void {
    this.loading = true
    // Pass business Parameters to parent params,
    this.params = { ...this.businessParameters, ...this.params, size: this.size }
    this.userService.getList(this.params).subscribe(response => {
      this.renderList(response)
      this.pageService.setTabScrollStatus(ETabScrollStatus.Scroll)
    })
  }

  goAddUser() {
    // businessCode can be 'insCode', 'intMerCode', 'intStoreCode', 'agentCode'
    const businessCode = this.route.parent.snapshot.paramMap.get('id')
    this.router.navigate(['users/new'], {
      queryParams: {
        insCode: this.insCode, // -- Mandatory, it to use in get role api.
        type: this.roleType, // -- Mandatory, it use to return the response to correct roles
        businessCode, // --Mandatory, it use to assign the user is created under which Role
      },
    })
  }

  getRoleName(item: User): string {
    try {
     return item.roles[0].roleName
    } catch (error) {
    return this.trans('GENERAL.INFO.NONE')
    }
  }

  createColumns(): STColumn[] {
    const canLock = this.aclService.canAbility('api.put.camel.user.one.freeze')
    const canUnlock = this.aclService.canAbility('api.put.camel.user.one.unfreeze')
    const canDelete = this.aclService.canAbility('api.delete.camel.user.one')
    const isEditable = this.aclService.canAbility(ECustomAcl.StoreEditable)
    return [
      {
        type: 'link',
        title: '用户名',
        i18n: 'USER.USERNAME',
        index: 'username',
        className: 'text-center',
        width: '150px',
        click: this.viewDetail.bind(this),
        fixed: 'left',
      },
      {
        title: '用户姓名',
        i18n: 'USER.NAME',
        index: 'nickName',
        width: '200px',
        className: 'text-left',
      },
      {
        title: '用户角色',
        i18n: 'USER.USER_ROLE',
        width: '200px',
        className: 'text-left',
        render: 'roleName',
      },
      {
        title: '电子邮箱',
        i18n: 'GENERAL.INFO.EMAIL',
        index: 'email',
        width: '200px',
        className: 'text-left',
      },
      {
        title: '操作',
        i18n: 'GENERAL.INFO.OPERATION',
        width: '150px',
        fixed: 'right',
        className: 'text-center',
        iif: () => isEditable && (canLock || canUnlock || canDelete),
        buttons: [
          {
            icon: {
              iconfont: 'icon-delete-circle',
              type: 'iconfont',
            },
            click: this.deleteUserDialog.bind(this),
            iif: () => canDelete,
          },
          {
            icon: {
              iconfont: 'icon-lock-twotone',
              type: 'iconfont',
            },
            click: this.freezeDialog.bind(this),
            iif: record => canLock && (record.status === 'normal' || record.status === ''), // status 有可能为空值
          },
          {
            icon: {
              iconfont: 'icon-unlock-circle',
              type: 'iconfont',
            },
            click: this.unfreezeUserDialog.bind(this),
            iif: record => canUnlock && record.status === 'freeze',
          },
        ],
      },
    ]
  }

  viewDetail(data: User) {
    this.router.navigate(['users', data.username])
  }

  freezeDialog(user: User) {
    const { username } = user
    this.modal.confirm({
      nzTitle: this.trans('GENERAL.NOTIFICATION.WARNING'),
      nzContent: this.trans('GENERAL.NOTIFICATION.USER_FREEZE_CONFIRM', {username}),
      nzOnOk: () => this.freezeUser(username),
    })
  }

  freezeUser(username: string): void {
    this.userService.freeze(username).subscribe(
      values => {
        // this.reloadTable.emit()
        this.st.reload()
        this.msg.success(this.trans('GENERAL.NOTIFICATION.FREEZE_SUCCESS'))
      },
      err => {
        console.error(err)
        this.msg.success(this.trans('GENERAL.NOTIFICATION.FREEZE_FAIL'))
      },
    )
  }

  // 解冻用户
  unfreezeUserDialog(user: User): void {
    this.modal.confirm({
      nzTitle: this.trans('GENERAL.NOTIFICATION.WARNING'),
      nzContent: this.trans('GENERAL.NOTIFICATION.USER_UNFREEZE_CONFIRM', {username: user.username}),
      nzOnOk: () => this.unfreezeUser(user.username),
    })
  }

  unfreezeUser(username: string): void {
    this.userService.unfreeze(username).subscribe(
      values => {
        // this.reloadTable.emit()
        this.st.reload()
        this.msg.success(this.trans('GENERAL.NOTIFICATION.UNFREEZE_SUCCESS'))
      },
      err => {
        console.error(err)
        this.msg.success(this.trans('GENERAL.NOTIFICATION.UNFREEZE_FAIL'))
      },
    )
  }

  // 刪除用户
  deleteUserDialog(user): void {
    this.modal.confirm({
      nzTitle: this.trans('GENERAL.NOTIFICATION.WARNING'),
      nzContent: this.trans('GENERAL.NOTIFICATION.USER_DELETE_CONFIRM', {username: user.username}),
      nzOnOk: () => this.deleteUser(user),
    })
  }

  deleteUser(user: User): void {
    this.userService.delete(user.username).subscribe(
      values => {
        // this.reloadTable.emit()
        this.st.reload()
        this.msg.success(this.trans('GENERAL.NOTIFICATION.DELETE_SUCCESS'))
      },
      err => {
        console.error(err)
        this.msg.success(this.trans('GENERAL.NOTIFICATION.DELETE_FAIL'))
      },
    )
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
